/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tree;

import java.util.List;

/**
 *
 * @author Ej-Dý
 */
public class CastIfTree extends VlastniProgramTree {

    private BinaryTree porovnani;
    private List<VlastniProgramTree> castIf;
    private List<VlastniProgramTree> castElse;

    public CastIfTree(Position start, Position end, BinaryTree porovnani, List<VlastniProgramTree> castIf, List<VlastniProgramTree> castElse) {
        super(start, end);
        this.porovnani = porovnani;
        this.castIf = castIf;
        this.castElse = castElse;
    }

    public BinaryTree getPorovnani() {
        return porovnani;
    }

    public List<VlastniProgramTree> getCastIf() {
        return castIf;
    }

    public List<VlastniProgramTree> getCastElse() {
        return castElse;
    }

    @Override
    public void accept(TreeVisitor visitor) {
        visitor.visitIf(this);
    }

    @Override
    public void generate(Context ctx) {
        String lab1 = ctx.nextLabel();

        ctx.addAttr("lab", lab1);
        porovnani.generate(ctx);
        ctx.removeAttr("lab");
        for (VlastniProgramTree vt : castIf) {
            vt.generate(ctx);
        }
        if (castIf == null) {
            ctx.println("label " + lab1 + ":");
        } else {
            String lab2 = ctx.nextLabel();
            ctx.println("goto " + lab2);
            ctx.println("label " + lab1 + ":");
            if (castElse != null) {
                for (VlastniProgramTree vt : castElse) {
                    vt.generate(ctx);
                }
            }
            ctx.println("label " + lab2 + ":");
        }
    }

    @Override
    public String toString() {
        return String.format("If %s: [%s, %s, %s]", super.toString(), porovnani, castIf, castElse);
    }
}
